package com.juntuo.youbo;


import com.alibaba.fastjson.JSON;
import com.juntuo.entity.DeviceHistory;
import com.juntuo.util.*;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 *  Auth:
 *  This interface is used to authenticate third-party systems before third-party systems access open APIs.
 */
public class AuthenticationUtil4Youbo {
    private static Logger log=Logger.getLogger(AuthenticationUtil4Youbo.class);
    @SuppressWarnings({ "resource", "unchecked" })
    public static String login() throws Exception {

        String apiKey = "02ACA587E95042A39587128A4130C5A2";
        String secret = "74C17098184241E4BC2BDCEAB7002C85";
        String urlLogin = "https://api-jt.union-park.cn/test/authorize/login";

        Map<String, String> param = new HashMap<>();
        param.put("ApiKey", apiKey);
        param.put("ApiSecret", secret);

//        String result=CommonHttpsUtil.doGet(urlLogin+"?api_key="+apiKey+"&api_secret="+secret);
        String result= CommonHttpsUtil.doPost(urlLogin,param);
        System.out.println(result);
        Map<String,Object> map =(Map<String,Object>)JSON.parse(result);
        if(Integer.parseInt(map.get("status_code").toString())==1){
            Map<String,Object> map1 =(Map<String,Object>)map.get("data");
            String token =map1.get("access_token").toString();

            return token;
        }

        //resolve the value of accessToken from responseLogin.
//        Map<String, String> data = new HashMap<>();
//        data = JsonUtil.jsonString2SimpleObj(responseLogin.getContent(), data.getClass());
//        String accessToken = data.get("accessToken");
//        System.out.println("accessToken:" + accessToken);
//        Cache.accessToken=accessToken;
//        Cache.refreshToken=data.get("refreshToken");
        return "";

    }


    public static String updateData(String token, DeviceHistory history) throws Exception {
        String url = "https://api-jt.union-park.cn/test/sensor/statuschanged";
        Map<String,Object> params = new HashMap<>(7);
        params.put("device_id",history.getDeviceId());
        params.put("status",Integer.parseInt(history.getStatus()));
        params.put("change_time",history.getCreateTime().getTime()/1000);
        params.put("remote_log_id",history.getId());
        params.put("signal_trust_ratio",100);
        params.put("electricity",history.getBatteryLevel());
        params.put("voltage",(0.012*history.getBatteryLevel())+3);
        String paramStr = JSON.toJSONString(params);

        String result = CommonHttpsUtil.doPost(url,paramStr,token);
        log.info(result +"---"+ paramStr);
        System.out.println(result);

        return result;
    }
}
